#!/bin/bash

TDIR=${1}
LIST=rom.list
boot_path=""
system_path=""

hex_str_to_int()
{
    number=$1
    hex=$(echo $number | cut -c 11- | tr [:lower:] [:upper:])
    echo "obase=10;ibase=16;$hex" | bc
}


unpack_rom()
{
    local f
    local ext
    f=$1
    ext=${f##*.}
    if [ "$ext" == "zip" ]; then
        boot_path=$(zipinfo -1 "$f" | grep "\bboot\.img$")
	    system_path=$(zipinfo -1 "$f" | grep -e "\bsystem\.img$" -e "\bsystem.new.dat$")

        if [ -z "$boot_path" ]; then
            zipinfo -1 "$f" | grep -e '.*\.zip$' -e '.*\.rar$' > tmp_files
            while read ff
                do
                    unzip -qo "$f" "$ff"
                    unpack_rom "$ff"
            done < tmp_files
         else

            echo "extracting $boot_path ..."
            unzip -qo "$f" "$boot_path"
            echo "extracting $system_path ..."
            unzip -qo "$f" "$system_path"
        fi

    elif [ "$ext" == "rar" ]; then
        boot_path=$(unrar lb "$f" | grep "\bboot\.img$")
	    system_path=$(unrar lb "$f" | grep -e "\bsystem\.img$" -e "\bsystem.new.dat$")

        if [ -z "$boot_path" ]; then
            unrar lb "$f" | grep -e '.*\.zip$' -e '.*\.rar$' > tmp_files
            while read ff
                do
                    unrar x -y "$f" "$ff"
                    unpack_rom "$ff"
            done < tmp_files
        else

            echo "extracting $boot_path ..."
            unrar x -y "$f" "$boot_path"
            echo "extracting $system_path ..."
            unrar x -y "$f" "$system_path"
        fi
    fi
}

extract_rom_info()
{
    f=$1

    DIR1=$(basename "$f")
	DIR="${DIR1%.*}"
    rm -rf "$DIR"
    mkdir "$DIR"
    pushd "$DIR"
    ret=0

    echo "unpacking rom $f ..."
    unpack_rom "$f"

    bootimg=$boot_path
    systemimg=$system_path

    if [ -z "$bootimg" -o -z "$systemimg" ]; then
        echo "can not find images, abort."
        ret=1
    fi

    echo "examing rom type ..."
    /usr/bin/strings "$systemimg" > system.img.strings
    abi=$(grep -m1 'ro.product.cpu.abi=' system.img.strings | sed 's/.*=//')

    echo "abi = $abi"
    if [ "$abi" != "arm64-v8a" ]; then
	echo "not 64 bit rom"
	ret=1
    fi

    popd
    rm -rf "$DIR"
    return $ret
}


### main

if [ $# -lt 1 ]; then
   echo "$0 <rom dir>"
   exit 1
fi

if [[ ! "$TDIR" =~ ^/ ]]; then
   echo "must use absolute path!"
   exit 1
fi

utils=("unzip" "unrar" "strings")

for u in ${utils[@]}
do 
which $u &>/dev/null
if [ $? -ne 0 ]; then
   echo "please install $u ."
   exit 1
fi
done

echo "scaning roms ..."
find "${TDIR}" -name "*.zip" > ${LIST}
find "${TDIR}" -name "*.rar" >> ${LIST}

echo "analyze roms ..."
rm -f rom-bad.list
rm -f rom-valid.list
while read f
do
    extract_rom_info "$f"
    if [ "$?" -ne 0 ]; then
	echo "$f" >> rom-bad.list
    else
	echo "$f" >> rom-valid.list
    fi
done < "${LIST}"

echo "rom-bad.list has BAD roms!"
echo "rom-valid.list has GOOD roms!"
echo "please run copy_rom.sh to copy GODD roms"

